package onlinecalsys.client.view.gui;

import java.awt.*;
import java.awt.event.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.rmi.RemoteException;

import javax.imageio.ImageIO;
import javax.swing.*;

import onlinecalsys.client.init.Onlinecalsys;
import onlinecalsys.client.view.UsernameValidation;

/**
 * Summary description for Login
 * 
 */
public class Login extends JFrame {
	// Variables declaration
	private JLabel jLabelUserName;
	private JLabel jLabelPassword;
	private JTextField jTextFieldUserName;
	private JTextField jTextFieldPassword;
	private JButton jButtonOK;
	private JButton jButtonNewUser;
	private JPanel contentPane;
	// End of variables declaration
	private UsernameValidation usernameVal;
	private Onlinecalsys onlinecalsys;

	public Login(Onlinecalsys onlinecalsys) {
		super();
		this.onlinecalsys = onlinecalsys;
		initializeComponent();

		// load frame logo
		BufferedImage image = null;
		try {
			URL u = this.getClass().getResource(
			"../../../../");
			File f = new File(u.getPath().replaceAll("bin/", "images/middle1.png"));
			System.out.println(f.getAbsolutePath());
			image = ImageIO.read(f);
			
			
		} catch (IOException e) {
			new Error("failed loading middle1.png");
		} catch (Exception e) {
			new Error("failed loading middle1.png");
		}
		this.setIconImage(image);
		// 
		// TODO: Add any constructor code after initializeComponent call
		// 

		this.setVisible(true);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
	}

	/**
	 * This method is called from within the constructor to initialize the form.
	 * WARNING: Do NOT modify this code. The content of this method is always
	 * regenerated by the Windows Form Designer. Otherwise, retrieving design
	 * might not work properly. Tip: If you must revise this method, please
	 * backup this GUI file for JFrameBuilder to retrieve your design properly
	 * in future, before revising this method.
	 */
	private void initializeComponent() {
		jLabelUserName = new JLabel();
		jLabelPassword = new JLabel();
		jTextFieldUserName = new JTextField();
		jTextFieldPassword = new JTextField();
		jButtonOK = new JButton();
		jButtonNewUser = new JButton();
		contentPane = (JPanel) this.getContentPane();
		usernameVal = new UsernameValidation();

		// 
		// jLabelUserName
		// 
		jLabelUserName.setText("UserName:");
		// 
		// jLabelPassord
		// 
		jLabelPassword.setText("Password:");
		// 
		// jTextFieldUserName
		// 
		jTextFieldUserName.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jTextFieldUserName_actionPerformed(e);
			}

		});
		// 
		// jTextFieldPassord
		// 
		jTextFieldPassword = new JPasswordField(10);

		jTextFieldPassword.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jTextFieldPassord_actionPerformed(e);
			}

		});
		// 
		// jButtonOK
		// 
		jButtonOK.setText("OK");
		jButtonOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jButtonOK_actionPerformed(e);
			}

		});
		// 
		jButtonNewUser.setText("New");
		jButtonNewUser.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				jButtonNewUser_actionPerformed(e);
			}

		});
		// contentPane
		// 
		contentPane.setLayout(null);
		addComponent(contentPane, jLabelUserName, 2, 13, 85, 18);
		addComponent(contentPane, jLabelPassword, 2, 45, 85, 18);
		addComponent(contentPane, jTextFieldUserName, 72, 13, 122, 22);
		addComponent(contentPane, jTextFieldPassword, 72, 42, 122, 22);
		addComponent(contentPane, jButtonOK, 156, 78, 55, 28);
		addComponent(contentPane, jButtonNewUser, 80, 78, 60, 28);
		// 
		// Login
		// 
		this.setTitle("Login - extends JFrame");
		this.setLocation(new Point(0, 1));
		this.setSize(new Dimension(224, 142));
		this.setResizable(false);
	}

	/** Add Component Without a Layout Manager (Absolute Positioning) */
	private void addComponent(Container container, Component c, int x, int y,
			int width, int height) {
		c.setBounds(x, y, width, height);
		container.add(c);
	}

	// 
	// TODO: Add any appropriate code in the following Event Handling Methods
	// 
	private void jTextFieldUserName_actionPerformed(ActionEvent e) {
		System.out
				.println("\njTextFieldUserName_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here

	}

	private void jTextFieldPassord_actionPerformed(ActionEvent e) {
		System.out
				.println("\njTextFieldPassord_actionPerformed(ActionEvent e) called.");
		// TODO: Add any handling code here

	}

	private void jButtonOK_actionPerformed(ActionEvent e) {
		try {
			// checking to see if the user has entered anything
			if (jTextFieldUserName.getText().trim().equals("")
					|| jTextFieldPassword.getText().trim().equals("")) {
				new Error("Sorry, you have to put a username or/and password");
			} else {
				// check in the database to see if username and pass is valid
				if (usernameVal.isValidUsernamePasswordCombination(
						jTextFieldUserName.getText(), jTextFieldPassword
								.getText())) {
					onlinecalsys.loginConfirmed(jTextFieldUserName.getText());
					dispose();
				} else {
					new Error("Sorry the login and password doesnt match");
				}

			}

		} catch (RemoteException e1) {
			e1.printStackTrace();
			new Error(
					"Sorry the is either no connection to the server or there is an internal server problem");
		} catch (Exception e2) {
			e2.printStackTrace();
			new Error(
					"Sorry the is either no connection to the server or there is an internal server problem");
		}
	}

	private void jButtonNewUser_actionPerformed(ActionEvent e) {
		try {
			// checking to see if the user has entered anything
			if (jTextFieldUserName.getText().trim().equals("")
					|| jTextFieldPassword.getText().trim().equals("")) {

				new Error("Sorry, you have to put a username or/and password");

			} else {
				// Put the new user into the database, if username already
				// exist==> error
				if (usernameVal.createNewUser(jTextFieldUserName.getText(),
						jTextFieldPassword.getText())) {

					Component frame = null;
					JOptionPane.showMessageDialog(frame,
							"Congrats, you have created a new user", "Info",
							JOptionPane.INFORMATION_MESSAGE);

				} else {
					new Error("Sorry the Username might already be taken");
				}

			}

		} catch (RemoteException e1) {
			e1.printStackTrace();
			new Error(
					"Sorry the is either no connection to the server or there is an internal server problem");
		} catch (Exception e2) {
			e2.printStackTrace();
			new Error(
					"Sorry the is either no connection to the server or there is an internal server problem");
		}
	}

	// ============================= Testing ================================//

	// public static void main(String[] args)
	// {
	// JFrame.setDefaultLookAndFeelDecorated(true);
	// JDialog.setDefaultLookAndFeelDecorated(true);
	// try
	// {
	// UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
	// }
	// catch (Exception ex)
	// {
	// System.out.println("Failed loading L&F: ");
	// System.out.println(ex);
	// }
	// new Login();
	// }
	// //= End of Testing =

}
